package com.fs.leetcode.shuzu.sum;

import java.util.*;

/**
 * 给定数组 nums = [1, 0, -1, 0, -2, 2]，和 target = 0。
 * @author huyunqiang
 * @Date 2019/10/20 14:18
 */
public class fourSum {

    /**
     *
     *   双指针和三数之和一样三数之和 只需要一层循环 a+b=-c,  left = i+1,right = nums.length-1; i
     *   四个数之和只是比第三个数多了一个循环 i, j=i+1
     *   c+d = target-a-b
     *   i, j=i+1, left=j+1,right = num.length-1
     *
     * @param nums
     * @param target
     * @return
     */
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        if (nums.length < 4) {
            return Collections.emptyList();
        }

        Arrays.sort(nums);

        List<List<Integer>> results = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j - 1 != i && nums[j] == nums[j - 1]) {
                    continue;
                }
                // 计算当前目标
                int currentTarget = target - nums[i] - nums[j];
                // 双指标遍历
                int left = j + 1, right = nums.length - 1;
                while (left < right) {
                    int sum = nums[left] + nums[right];
                    // 符合条件
                    if (sum == currentTarget) {
                        results.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        // 右移
                        do {
                            left++;
                        } while (left < right && nums[left] == nums[left - 1]);
                        // 左移
                        do {
                            right--;
                        } while (left < right && nums[right] == nums[right + 1]);
                        continue;
                    }
                    // 过小
                    if (sum < currentTarget) {
                        // 右移
                        do {
                            left++;
                        } while (left < right && nums[left] == nums[left - 1]);
                        continue;
                    }
                    // 过大
                    // 左移
                    do {
                        right--;
                    } while (left < right && nums[right] == nums[right + 1]);
                }
            }
        }

        return results;
    }

    public static void main(String[] args) {
        int arr[] = {1, 0, -1, 0, -2, 2};
        int target = 0;
        Long start = System.currentTimeMillis();
        fourSum(arr,target);
        Long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}
